class WebSocketIO {
	/**
	 * @param {Object} busId 业务ID
	 * @param {Object} url ws地址
	 * @param {Object} retryTime 重试时间
	 */
	constructor(busId,url,retryTime) {
        this.socketTask = null //socket 连接对象
		this.is_open_socket = false //避免重复连接
		this.url = url + busId  //socket连接地址
		this.connectNum = 1 // 当前连接次数
		this.maxConnectNum = 10 //重连次数
		this.isInitiative = false // 是否主动断开
		this.retryTime = retryTime ? retryTime : 15000 //重试时间-多少秒执行检测
		this.reconnection = 5000 //重连时间
		this.heartbeatInterval = null //检测服务器端是否还活着
		this.reconnectTimeOut = null //重连之后多久再次重连
		this.socketMsgEvent = 'socketMsg'
	}
 
	// 进入这个页面的时候创建websocket连接【整个页面随时使用】
	connectSocketInit() {
		//连接socket
		this.socketTask = uni.connectSocket({
			url: this.url,
			success: () => {
				console.log("正准备建立websocket中...");
				// 返回实例
				return this.socketTask
			},
		});
		this.socketTask.onOpen((res) => {
			this.connectNum = 1
			console.log("WebSocket连接正常！");
			clearInterval(this.reconnectTimeOut)
			clearInterval(this.heartbeatInterval)
			this.is_open_socket = true;
			//开启心跳检测
			this.startHeartbeat();
			// 注：只有连接正常打开中 ，才能正常收到消息
			this.socketTask.onMessage((res) => {
				if (res.data) {
					console.log(res.data);
					uni.$emit(this.socketMsgEvent, res.data); 
				}
			});
		})
		// 监听连接失败，这里代码我注释掉的原因是因为如果服务器关闭后，和下面的onclose方法一起发起重连操作，这样会导致重复连接
		uni.onSocketError((res) => {
			console.log('WebSocket连接打开失败，请检查！');
			this.socketTask = null
			this.is_open_socket = false;
			clearInterval(this.heartbeatInterval)
			clearInterval(this.reconnectTimeOut)
			
			if (this.connectNum <= this.maxConnectNum) {
				uni.showToast({
					title: `连接失败，正尝试第${this.connectNum}次连接`,
					icon: "none"
				})
				this.reconnect();
				this.connectNum += 1
				
			} else {
				uni.$emit('connectError');
				this.connectNum = 1
			}
 
		});
		// 这里仅是事件监听【如果socket关闭了会执行】
		this.socketTask.onClose(() => {
			console.log("socket已经被关闭了-------")
			clearInterval(this.heartbeatInterval)
			clearInterval(this.reconnectTimeOut)
			this.is_open_socket = false;
			this.socketTask = null
			
			if (this.connectNum <= this.maxConnectNum) {
				this.reconnect();
			} else {
				uni.$emit('connectError');
				this.connectNum = 1
			}
 
		})
	}
    // 主动关闭socket连接
	closeSocket() {
		if (!this.is_open_socket) {
			return
		}
		const _this = this
		
		this.socketTask.close({
			success() {
				//移除事件
				uni.$off(_this.socketMsgEvent)
				_this.isInitiative = true
				_this.is_open_socket = false
				_this.socketTask = null 
				_this.connectNum = 1
				clearInterval(_this.heartbeatInterval)
				clearInterval(_this.reconnectTimeOut)
				// uni.showToast({
				// 	title: 'SocketTask 关闭成功',
				// 	icon: "none"
				// });
			}
		});
	}
	//发送消息
	send(data) {
		// 注：只有连接正常打开中 ，才能正常成功发送消息
		if (this.socketTask) {
			this.socketTask.send({
				data: JSON.stringify(data),
				async success() {
					uni.$emit('sendSuccess'); 
				},
			});
		}
	}
	//开启心跳检测
	startHeartbeat() {
		this.heartbeatInterval = setInterval(() => {
			this.send({
				"state": 'heartbeat',
				"type": "ping"
			});
		}, this.retryTime)
	}
	//重新连接
	reconnect() {
		//停止发送心跳
		clearInterval(this.heartbeatInterval)
		//如果不是人为关闭的话，进行重连
		if (!this.is_open_socket &&  !this.isInitiative) {
			this.reconnectTimeOut = setInterval(() => {
				this.connectSocketInit();
			}, this.reconnection)
		}
	}
	
}
module.exports = WebSocketIO